package ltu.m7011e.server.rpc;

import java.util.ArrayList;
import java.util.Collection;

import ltu.m7011e.client.GreetingService;
import ltu.m7011e.server.pojo.LinkEntity;
import ltu.m7011e.server.response.link.LinkResponse;
import ltu.m7011e.server.service.impl.LinkService;
import ltu.m7011e.shared.FieldVerifier;
import ltu.m7011e.shared.model.Link;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	
	private LinkService myLinkService = new LinkService();

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}
	
	public Collection<Link> getNewestLinks(){
		Collection<Link> myLinks = new ArrayList<Link>();
		
		// TODO call service loadNewestLinks() ? directly or can Inject ?

		return myLinks;
	}
	
	public String postLink(Link newLink){
		
		// TODO : work/modify for implement of Exception Handling 
		LinkResponse mockLink = new LinkResponse();
		myLinkService.doPost(mockLink);
		
		return "Post operation always go well =)";
	}
	
	public String sendLikeToServer(Integer linkId){
		myLinkService.addLikeTo(linkId);
		
		return "Like operation always go well =)";
	}
	
	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
